const util = require('util')
const { WX } = require('../../config/config')
const axios = require('axios')
const User = require('../../db/model/user')
const { generateToken } = require('../../core/util')

class WXManager {
  static async codeToToken(code) {
    const appId = WX.appId
    const secret = WX.secret
    const loginUrl = WX.loginUrl

    const url = util.format(loginUrl, appId, secret, code)

    const result = await axios.get(url)

    if (result.status !== 200) {
      throw new global.errs.AuthFailed('获取openId失败')
    }

    // console.log(result.data) 
    const openid = result.data.openid
    if (!openid) {
      throw new global.errs.AuthFailed('获取openId失败')
    }

    let user = await User.getUserByOpenid(openid)
    if (!user) {
      user = await User.addUserByOpenid(openid)
    }

    return generateToken(user.id, 8)
  }
}

module.exports = WXManager